import pinia from "@/store";
import { useAppStore } from "@/store/modules/app";
import { getToken } from "@/utils/utils";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { appRoutes } from "./routes";
import { NOT_FOUND_ROUTE } from "./routes/base";

const appStore = useAppStore(pinia);

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "login"
  },
  {
    path: "/login",
    name: "login",
    meta: {},
    component: () => import("@/views/login/index.vue")
  },
  ...appRoutes,
  NOT_FOUND_ROUTE
];
// 路由
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }) // 刷新时，滚动条位置还原
});

// 全局守卫：登录拦截 本地没有存token,请重新登录
router.beforeEach((to, from, next) => {
  // 判断有没有登录
  if (!getToken()) {
    if (to.name === "login") {
      next();
    } else {
      router.push("login");
    }
  } else {
    if (!appStore.isRoutesLoaded) {
      appStore.getMenuList();
    }
    if (to.name === "login") {
      // next({ path: from.path });
      next({ path: "/home" });
    }
    next();
  }
  // next();
});

// 导出
export default router;
